//
//  PicturePickerController.swift
//  照片选择
//
//  Created by 孙明海 on 16/2/18.
//  Copyright © 2016年 孙明海. All rights reserved.
//

import UIKit

/// 照片选择器 cell 重用ID
private let picturePickerCellID = "picturePickerCellID"
private let pictureMaxCount = 3

class PicturePickerController: UICollectionViewController {
    /// 配图数组
    lazy var pictures = [UIImage]()
    /// 当前用户选中cell 的索引
    var selectedIndex = 0
    
    /// 生命周期函数
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1)
        self.collectionView!.registerClass(PicturePickerCell.self, forCellWithReuseIdentifier: picturePickerCellID)
    }
    
    /// 构造函数
    init() {
        super.init(collectionViewLayout: PicturePickerLayout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 照片选择器布局
    private class PicturePickerLayout: UICollectionViewFlowLayout {
        override private func prepareLayout() {
             super.prepareLayout()
            
            let count: CGFloat = 4
            let margin: CGFloat = UIScreen.mainScreen().scale * 4
            let width = (collectionView!.bounds.width - (count + 1) * margin) / count
            itemSize = CGSizeMake(width, width)
            sectionInset = UIEdgeInsetsMake(margin, margin, 0, margin)
            minimumInteritemSpacing = margin
            minimumLineSpacing = margin
        }
    }
    
}

// MARK: UICollectionViewDataSource
extension PicturePickerController {
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictures.count + (pictures.count < pictureMaxCount ? 1 : 0)
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(picturePickerCellID, forIndexPath: indexPath) as! PicturePickerCell
        cell.image = (indexPath.item < pictures.count) ? pictures[indexPath.item] : nil
        cell.picturePickerDelegate = self
        
        return cell
    }
}
// MARK: - PicturePickerCellDelegate
extension PicturePickerController: PicturePickerCellDelegate {
    
    @objc private func picturePickerCellDidAdd(picturePickerCell: PicturePickerCell) {
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
            print("无法访问照片库")
            return
        }
        
        self.selectedIndex = collectionView?.indexPathForCell(picturePickerCell)?.item ?? 0
        let picker = UIImagePickerController()
        picker.allowsEditing = true
        picker.delegate = self
        presentViewController(picker, animated: true) { () -> Void in
            
        }
    }
    @objc private func picturePickerCellDidRemove(picturePickerCell: PicturePickerCell) {
        selectedIndex = (collectionView?.indexPathForCell(picturePickerCell)?.item)!
        pictures.removeAtIndex(selectedIndex)
//        collectionView?.deleteItemsAtIndexPaths([NSIndexPath(forItem: selectedIndex, inSection: 0)])
        collectionView?.reloadData()
    }
}
// MARK: - UIImagePickerControllerDelegate,UINavigationControllerDelegate
extension PicturePickerController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        var image = info[UIImagePickerControllerEditedImage] as! UIImage
        image = image.scaleToWidth(600)
        if selectedIndex >= pictures.count {
            pictures.append(image)
        } else {

            pictures[self.selectedIndex] = image
        }
        
        dismissViewControllerAnimated(true) { () -> Void in
        self.collectionView?.reloadData()
        }
    }
}

/// PicturePickerCellDelegate 协议
@objc
private protocol PicturePickerCellDelegate: NSObjectProtocol {
    /// 添加图片
    optional func picturePickerCellDidAdd(picturePickerCell: PicturePickerCell)
    /// 删除图片
    optional func picturePickerCellDidRemove(picturePickerCell: PicturePickerCell)
}

/// 照片选择器 cell
private class PicturePickerCell: UICollectionViewCell {
    
    var image: UIImage? {
        didSet {
            addButton.setImage(image ?? UIImage(imageLiteral: "compose_pic_add"), forState: .Normal)
            removeButton.hidden = (image == nil)
        }
    }
    /// 照片选择器代理
    weak var picturePickerDelegate: PicturePickerCellDelegate?
    
    //MARK: - 监听方法
    @objc func addPicture() {
        picturePickerDelegate?.picturePickerCellDidAdd?(self)
    }
    @objc func removePicture() {
        picturePickerDelegate?.picturePickerCellDidRemove?(self)
    }
    
    /// 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /// 设置控件
    private func setupUI() {
        //添加控件
        addSubview(addButton)
        addSubview(removeButton)
        
        //布局子控件
        addButton.frame = bounds
        removeButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
        // 监听方法
        addButton.addTarget(self, action: "addPicture", forControlEvents: .TouchUpInside)
        removeButton.addTarget(self, action: "removePicture", forControlEvents: .TouchUpInside)
        
        // 设置图片的填充模式
        addButton.imageView?.contentMode = .ScaleAspectFill
    }
    
    //MARK: - 懒加载控件
    /// 添加图片按钮
    private lazy var addButton: UIButton = UIButton(imageName: "compose_pic_add", backImageName: nil)
    /// 删除图片按钮
    private lazy var removeButton: UIButton = UIButton(imageName: "compose_photo_close", backImageName: nil)
}
